/*
 * Copyright (C) 2007  Vianney le Clément
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package fsahoraires.gui.pages;

import java.util.NoSuchElementException;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.*;

import fsahoraires.gui.MainWindow;
import fsahoraires.programmes.Semestre;

public class RootSemestresPage extends ListPage {

	private MainWindow main;
	private Spinner annee;
	private Button semestre1, semestre2;

	public RootSemestresPage(MainWindow main) {
		super("Quadrimestres", "semestre_edit.png");
		this.main = main;
	}

	@Override
	protected Control createEntry(Composite parent) {
		Composite comp = new Composite(parent, SWT.NONE);
		comp.setLayout(new RowLayout(SWT.HORIZONTAL));
		Label label = new Label(comp, SWT.NONE);
		label.setText("Année : ");
		label.pack();
		annee = new Spinner(comp, SWT.BORDER);
		annee.setSelection(888);
		annee.pack();
		annee.setSelection(1);
		annee.setMinimum(1);
		annee.setMaximum(10);
		semestre1 = new Button(comp, SWT.RADIO);
		semestre1.setText("Premier quadrimestre");
		semestre1.setSelection(true);
		semestre2 = new Button(comp, SWT.RADIO);
		semestre2.setText("Second quadrimestre");
		return comp;
	}

	@Override
	protected void initTable() {
		initColumns(new String[] { "Quadrimestre", "Crédits", "h/semaine" },
				new int[] { SWT.LEFT, SWT.CENTER, SWT.CENTER });
	}

	protected void packColumns(int width) {
		for (int i = 1; i < table.getColumnCount(); i++) {
			table.getColumn(i).pack();
			width -= table.getColumn(i).getWidth();
		}
		table.getColumn(0).setWidth(width);
	}

	@Override
	public void update() {
		table.removeAll();

		for (Semestre semestre : main.getProgramme()) {
			addSemestre(semestre);
		}
	}

	private void addSemestre(Semestre semestre) {
		TableItem ti = new TableItem(table, SWT.NONE);
		ti.setText(0, semestre.toString());
		ti.setText(1, semestre.getCredits() + "");
		ti.setText(2, (semestre.getHoraire().getOccupationsCount() * 2) + "");
		ti.setData(semestre);
	}

	@Override
	protected void add() {
		try {
			new Semestre(main.getProgramme(), annee.getSelection(), (semestre1
					.getSelection() ? 1 : 2));
		} catch (NoSuchElementException e) {
		}
	}

	@Override
	protected void remove() {
		for (TableItem ti : table.getSelection())
			((Semestre) ti.getData()).dispose();
	}

}
